package parknfly

import (
	"encoding/json"
	"fmt"
	"parking-lot-go-push/model"
	"parking-lot-go-push/model/cars"
	"parking-lot-go-push/model/order"
	"parking-lot-go-push/model/park"
	"parking-lot-go-push/mongodb"
)

type OutStruct struct {
	mongodb.CarsOutMongoDbStruct
}

// 出场通知
func (outData OutStruct) Out() {
	parknflyPushLogger.Info(" ")
	parknflyPushLogger.Info("---出场推送---")
	jsonData, _ := json.Marshal(outData)
	parknflyPushLogger.Info(fmt.Sprintf("参数:%s", string(jsonData)))

	//错误信息
	var err error

	//查询订单
	var orderData order.OrderStruct
	if _, err = orderData.FetchOrder(outData.OrderNo, 1, 2); err != nil {
		parknflyPushLogger.Error(fmt.Sprintf("订单查询失败:%s", err.Error()))
		return
	}

	//查询泊安飞订单
	var orderParknflyStruct order.OrderParknflyStruct
	orderParknflyData, err := orderParknflyStruct.FetchOrder(outData.OrderNo, 1)
	if err != nil {
		parknflyPushLogger.Error(fmt.Sprintf("泊安飞订单查询失败:%s", err.Error()))
		return
	}

	//超停状态
	if _, err := orderData.OverStop(outData.ParkCode, 2, outData.OrderNo); err != nil {
		parknflyPushLogger.Error(err.Error())
		return
	}

	//查询泊安飞停车场信息
	var parkingLotParknflyData park.ParkingLotParknflyStruct
	_, err = model.GetModelDataFirst(
		model.Db,
		parkingLotParknflyData.TableName(),
		&parkingLotParknflyData,
		model.QueryOptions{
			Conditions: map[string]interface{}{
				"park_code": outData.ParkCode,
			},
		})

	//推送泊安飞出场信息
	parknflyOutPushData := map[string]interface{}{
		"parkKey": parkingLotParknflyData.ParkKey,
		"carNo":   outData.CarNumber,
		"outTime": outData.OutTime,
		"upType":  1,
		"orderNo": outData.OrderNo,
	}

	var carsOutStruct cars.CarsOutStruct

	//加密信息计算
	parknflySigner := NewSigner()
	if err, _ := parknflySigner.CurlPostJson("carOut", parknflyOutPushData); err != nil {
		parknflyPushLogger.Error("错误:推送失败", err.Error())

		//失败状态更新
		if err := carsOutStruct.PushError(outData.OrderNo, outData.PushErrNum); err != nil {
			parknflyPushLogger.Error(err.Error())
		}

	} else {

		//解绑参数
		unBindCarData := map[string]interface{}{
			"carId":      outData.CarNumber,
			"phone":      orderParknflyData.Mobile,
			"carType":    outData.CarType,
			"carnoColor": outData.CarNoColor,
		}

		//成功状态更新
		if err := carsOutStruct.PushSuccess(outData.OrderNo, outData.OutTime, 2, unBindCarData); err != nil {
			parknflyPushLogger.Error(err.Error())
		}
	}
}
